<template>
    <view class="pb-150">
        <image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
            mode="aspectFill"></image>
        <u-navbar title="快检巡监员管理" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
            :titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder></u-navbar>

        <!-- 顶部搜索与筛选 -->
        <view class="filter-wrap">
            <u-search v-model="query.keyword" placeholder="请输入姓名/账号/手机号" showAction actionText="搜索" @search="onSearch"
                :actionStyle="{ color: '#0A993B' }" :height="30" :inputStyle="{ fontSize: '28rpx' }" />

            <view class="row">
                <u--input v-model="form.workUnit" placeholder="请输入所属部门" class="f-input" />
                <!-- <text class="label">所属部门</text>
                <u-picker :show="showDept" :columns="[deptOptions]" @confirm="deptConfirm" @cancel="showDept = false" />
                <view class="picker-input" @click="showDept = true">
                    {{ query.workUnit || '全部' }}
                    <u-icon name="arrow-down" size="16" color="#999" />
                </view> -->
            </view>
        </view>

        <!-- 列表 -->
        <view class="list-wrap">
            <view class="card" v-for="item in filteredList" :key="item.id">
                <view class="kv"><text class="name">{{ item.inspectorName }}</text><text class="sex">{{ item.sex == '0'
                        ? '男' : item.sex == '1' ? '女' : '未知' }}</text></view>
                <view class="kv">账号：{{ item.userLogin }}</view>
                <view class="kv">手机号：{{ item.phoneNumber }}</view>
                <view class="kv">所属部门：{{ item.workUnit }}</view>
                <view class="ops">
                    <u-button size="small" text="编辑" @click="onEdit(item)"
                        :customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }" />
                    <u-button size="small" text="删除" type="error" plain @click="onDelete(item)"
                        :customStyle="{ border: '1px solid #0A993B', color: '#0A993B' }" />
                </view>
            </view>
            <view v-if="filteredList.length === 0" class="empty">
                <u-empty mode="data" icon="data"></u-empty>
            </view>
        </view>
        <view @tap="submit()" class="w-690 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
            style="bottom: 68rpx;left: 30rpx;">
            添加
        </view>

        <!-- 添加/编辑 弹框 -->
        <u-popup :show="showForm" mode="center" round="12" @close="showForm = false">
            <view class="form-wrap">
                <view class="form-title">{{ isEdit ? '编辑巡检员' : '添加巡检员' }}</view>

                <view class="form-row">
                    <text class="f-label">姓名：</text>
                    <u--input v-model="form.inspectorName" placeholder="请输入姓名" class="f-input" />
                </view>
                <view class="form-row">
                    <text class="f-label">账号：</text>
                    <u--input v-model="form.userLogin" placeholder="请输入账号" class="f-input" />
                </view>
                <view class="form-row">
                    <text class="f-label">性别：</text>
                    <u-radio-group v-model="form.sex" placement="row">
                        <u-radio :name="0">男</u-radio>
                        <u-radio :name="1">女</u-radio>
                        <u-radio :name="2">未知</u-radio>
                    </u-radio-group>
                </view>
                <view class="form-row">
                    <text class="f-label">所属部门：</text>
                    <u--input v-model="form.workUnit" placeholder="请输入所属部门" class="f-input" />
                    <!-- <u-picker :show="showFormDept" :columns="[deptOptions]" @confirm="formDeptConfirm"
                        @cancel="showFormDept = false" />
                    <view class="picker-input" @click="showFormDept = true">
                        {{ form.workUnit || '请选择部门' }}
                        <u-icon name="arrow-down" size="16" color="#999" />
                    </view> -->
                </view>
                <view class="form-row">
                    <text class="f-label">手机号：</text>
                    <u--input v-model="form.phoneNumber" placeholder="请输入手机号" class="f-input" />
                </view>

                <view class="form-actions">
                    <u-button size="small" text="保存" @click="saveForm"
                        :customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff', flex: 1 }" />
                    <u-button size="small" text="返回" @click="showForm = false" :customStyle="{ flex: 1 }" />
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import { inspector, addInspector, deleteInspector, editInspector } from '@/api/kuaijian'
export default {
    mixins: [navbarMixin],
    data() {
        return {
            query: { keyword: '', workUnit: '全部' },
            showDept: false,
            deptOptions: ['全部', '济南市林业局', '泰安市林业局', '烟台市林业局'],
            users: [],
            showForm: false,
            isEdit: false,
            editId: null,
            form: { inspectorName: '', userLogin: '', sex: '男', workUnit: '', phoneNumber: '' },
            showFormDept: false
        }
    },
    computed: {
        filteredList() {
            const kw = (this.query.keyword || '').trim();
            return (this.users || []).filter(v => {
                const okKw = !kw || [v.inspectorName, v.userLogin, v.phoneNumber].some(x => x && (x + "").includes(kw))
                const okDept = (this.query.workUnit === '全部') || v.workUnit === this.query.workUnit
                return okKw && okDept
            })
        }
    },
    methods: {
        onSearch() { /* 本地筛选已实时生效，这里预留 */ },
        deptConfirm(e) { this.query.workUnit = e.value[0]; this.showDept = false },
        onEdit(item) {
            this.isEdit = true;
            this.editId = item.id;
            this.form = { 
                inspectorName: item.inspectorName, 
                userLogin: item.userLogin, 
                sex: item.sex, 
                workUnit: item.workUnit, 
                phoneNumber: item.phoneNumber 
            };
            this.showForm = true;
        },
        onDelete(item) {
            uni.showModal({
                title: '提示', content: `确定删除“${item.inspectorName}”吗？`, success: ({ confirm }) => {
                    if (confirm) {
                        deleteInspector(item.id).then(res => {
                            console.log(res);
                            this.users = this.users.filter(v => v.id !== item.id); uni.showToast({ title: '已删除', icon: 'none' })
                        })
                    }
                }
            })
        },
        submit() {
            this.isEdit = false;
            this.editId = null;
            this.form = { inspectorName: '', userLogin: '', sex: '男', workUnit: '', phoneNumber: '' };
            this.showForm = true;
        },
        formDeptConfirm(e) { this.form.workUnit = e.value[0]; this.showFormDept = false },
        saveForm() {
            if (!this.form.inspectorName) { return uni.showToast({ title: '请输入姓名', icon: 'none' }) }
            if (!this.form.userLogin) { return uni.showToast({ title: '请输入账号', icon: 'none' }) }
            if (!this.form.workUnit) { return uni.showToast({ title: '请选择部门', icon: 'none' }) }
            if (!this.form.phoneNumber) { return uni.showToast({ title: '请输入手机号', icon: 'none' }) }
            if (this.isEdit) {
                // 编辑时调用编辑API，传递完整的字段数据
                const originalItem = this.users.find(v => v.id === this.editId);
                const editData = {
                    id: this.editId,
                    inspectorName: this.form.inspectorName,
                    userLogin: this.form.userLogin,
                    sex: this.form.sex,
                    workUnit: this.form.workUnit,
                    phoneNumber: this.form.phoneNumber,
                    createBy: originalItem?.createBy || '',
                    createTime: originalItem?.createTime || '',
                    delFlag: originalItem?.delFlag || '0',
                    status: originalItem?.status || '0',
                    updateBy: originalItem?.updateBy || '',
                    updateTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
                    remark: originalItem?.remark || null
                };
                
                editInspector(editData).then(res => {
                    console.log('编辑成功:', res);
                    // 更新本地列表
                    const idx = this.users.findIndex(v => v.id === this.editId);
                    if (idx > -1) { 
                        this.users.splice(idx, 1, editData);
                    }
                    uni.showToast({ title: '已保存', icon: 'none' });
                    this.showForm = false;
                }).catch(err => {
                    console.error('编辑失败:', err);
                    uni.showToast({ title: '保存失败', icon: 'none' });
                });
            } else {
                // 添加时调用添加API
                addInspector(this.form).then(res => {
                    console.log('添加成功:', res);
                    const newId = res.data?.id || Date.now();
                    this.users.unshift({ 
                        id: newId, 
                        ...this.form,
                        createBy: '',
                        createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
                        delFlag: '0',
                        status: '0',
                        updateBy: '',
                        updateTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
                        remark: null
                    });
                    uni.showToast({ title: '添加成功', icon: 'none' });
                    this.showForm = false;
                }).catch(err => {
                    console.error('添加失败:', err);
                    uni.showToast({ title: '添加失败', icon: 'none' });
                });
            }
        },
        // 获取列表
        getInspectorList() {
            inspector({ pageNum: 1, pageSize: 10 }).then(res => {
                console.log(res);
                this.users = res.rows
                console.log(this.users);
            })
        },
        // 编辑
        editInspector(data) {
            editInspector(data).then(res => {
                console.log(res);
            })
        }
    },
    onLoad() {
        this.getInspectorList()
    }
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;

    z-index: 1;
}

.filter-wrap {
    background: #fff;
    margin: 20rpx;
    padding: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.row {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-top: 16rpx;
}

.label {
    color: #666;
    width: 150rpx;
}

.picker-input {
    flex: 1;
    height: 72rpx;
    padding: 0 20rpx;
    background: #f5f5f5;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #333;
}

.list-wrap {
    margin: 20rpx;
}

.card {
    background: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.kv {
    margin: 8rpx 0;
    color: #333;
}

.name {
    font-size: 30rpx;
    font-weight: 600;
    margin-right: 16rpx;
}

.sex {
    color: #666;
}

.ops {
    margin-top: 14rpx;
    display: flex;
    gap: 12rpx;
}

.empty {
    padding: 80rpx 0;
}

/* 表单弹框样式 */
.form-wrap {
    width: 640rpx;
    padding: 24rpx;
    background: #fff;
    border-radius: 12rpx;
}

.form-title {
    text-align: center;
    font-size: 30rpx;
    font-weight: 600;
    margin-bottom: 12rpx;
}

.form-row {
    display: flex;
    align-items: center;
    gap: 20rpx;
    margin: 30rpx 0;
}

.f-label {
    text-align: right;
    width: 150rpx;
    color: #333;
}

.f-input {
    flex: 1;
}

.form-actions {
    display: flex;
    gap: 16rpx;
    margin-top: 10rpx;
}
</style>